<template>
  <div>
    <el-form ref="addFormRef" :rules="rules" :model="addForm.data">
      <el-form-item>
        <el-tree
          ref="treeRef"
          style="max-width: 600px"
          :data="menuTreeList.data"
          show-checkbox
          node-key="id"
          default-expand-all
          :props="propsList"
          :default-checked-keys="defaultCheckedKeys"
          @check-change="handleCheckChange"
          @node-click="handleNodeClick"
        />
      </el-form-item>
      <el-form-item>
        <div class="footer">
          <div></div>
          <div>
            <el-button class="reset-btn" @click="resetForm(addFormRef)">重 置</el-button>
            <el-button class="confirm-btn" @click="submitForm(addFormRef)"
              >确 认</el-button
            >
          </div>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { roleMenuIdsApi, getMenusApi } from "../request.js";
const emits = defineEmits(["operationDone"]);

const props = defineProps({
  operationId: {
    type: Object,
    default: () => {},
  },
  listData: {
    type: Object,
    default: () => {},
  },
});

console.log(props.operationId);

const propsList = {
  label: "name",
  children: "nodes",
};

const addFormRef = ref("");
const addForm = reactive({
  data: {
    items: [],
  },
});
const treeRef = ref(null);

const handleCheckChange = (data, checked) => {
  if (checked) {
    // 仅当 checkedIds 中不存在此 ID 时才添加
    if (!addForm.data.items.includes(data.id)) {
      addForm.data.items.push(data.id);
      addFormRef.value.validateField("items");
    }
  } else {
    // 移除 ID
    const index = addForm.data.items.indexOf(data.id);
    if (index !== -1) {
      addForm.data.items.splice(index, 1);
    }
  }
};

const handleNodeClick = (data, node) => {
  // 切换节点的选中状态
  const isCurrentlyChecked = node.checked;
  node.setChecked(!isCurrentlyChecked);

  // 根据新的选中状态更新 checkedIds 数组
  if (!isCurrentlyChecked) {
    // 如果节点之前未选中，则添加 ID
    if (!addForm.data.items.includes(data.id)) {
      addForm.data.items.push(data.id);
      addFormRef.value.validateField("items");
    }
  } else {
    // 如果节点之前已选中，则移除 ID
    const index = addForm.data.items.indexOf(data.id);
    if (index !== -1) {
      addForm.data.items.splice(index, 1);
    }
  }
};

const rules = reactive({
  items: [{ required: true, message: "请选择菜单权限", trigger: "change" }],
});

const resetForm = async (formEl) => {
  if (!formEl) return;
  if (treeRef.value) {
    treeRef.value.setCheckedKeys([]);
  }
  // 清空 checkedIds 数组
  addForm.data.items = [];
  formEl.resetFields();
};

const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      getMenusApi({
        id: props.operationId.id,
        data: addForm.data.items,
      }).then((res) => {
        if (res.data.code === 0) {
          ElMessage({
            type: "success",
            message: res.data.result,
          });
          emits("operationDone");
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    }
  });
};

const list = reactive({
  data: [],
});

const defaultCheckedKeys = ref('');

const init = async () => {
  await roleMenuIdsApi(props.operationId.id).then((res) => {
    console.log(res);
      list.data = res.data.result;
    defaultCheckedKeys.value = list.data
    // if (list.data) {
    //   const keys = menuTreeList.data
    //     .filter((item) => list.data.includes(item.id))
    //     .map((item) => item.id);

    //   // 设置选中的节点
    //   if (treeRef.value) {
    //     treeRef.value.setCheckedKeys(keys);
    //   }
    // }
  });
};

const menuTreeList = reactive({
  data: [],
});

onMounted(() => {
  menuTreeList.data = props.listData.menuTreeList;
  init();
});
</script>

<style lang="less" scoped>
.footer {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.reset-btn {
  width: 65px;
  height: 32px;
  background: #ffffff;
  border-radius: 2px;
  border: 1px solid #d9d9d9;
  font-weight: 400;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.65);
}

.confirm-btn {
  width: 65px;
  height: 32px;
  background: #007aff;
  border-radius: 2px;
  font-weight: 400;
  font-size: 14px;
  color: #ffffff;
}
</style>
